import requests
import time
import random
from typing import Dict, Any, List, Optional

class BilibiliAPI:
    def __init__(self, headers: Dict[str, str]):
        self.session = requests.Session()
        self.session.headers.update(headers)
        
    def search_videos(self, keyword: str, page: int = 1) -> Dict[str, Any]:
        """搜索视频"""
        url = 'https://api.bilibili.com/x/web-interface/search/type'
        params = {
            'keyword': keyword,
            'page': page,
            'order': 'totalrank',  # 综合排序
            'search_type': 'video',
            'tids': 0,
            'duration': 0,
            'platform': 'pc'
        }
        return self._make_request(url, params)
        
    def get_video_info(self, bvid: str) -> Dict[str, Any]:
        """获取视频信息"""
        url = f'https://api.bilibili.com/x/web-interface/view'
        params = {'bvid': bvid}
        return self._make_request(url, params)
        
    def get_video_danmaku(self, cid: str) -> List[str]:
        """获取视频弹幕"""
        url = f'https://api.bilibili.com/x/v1/dm/list.so?oid={cid}'
        try:
            response = self.session.get(url)
            response.encoding = 'utf-8'
            # 使用正则表达式提取弹幕内容
            import re
            pattern = re.compile(r'<d p="[^"]*">([^<]*)</d>')
            danmaku = pattern.findall(response.text)
            return danmaku
        except Exception as e:
            print(f"获取弹幕失败: {e}")
            return []
            
    def _make_request(self, url: str, params: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
        """发送请求并处理响应"""
        max_retries = 3
        for _ in range(max_retries):
            try:
                # 随机延迟0.5-1.5秒
                time.sleep(random.uniform(0.5, 1.5))
                
                # 更新User-Agent
                self.session.headers.update({
                    'User-Agent': f'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/{random.randint(80, 120)}.0.0.0',
                })
                
                response = self.session.get(url, params=params, timeout=10)
                response.raise_for_status()
                return response.json()
            except Exception as e:
                print(f"请求失败: {e}")
                time.sleep(2)  # 失败后等待2秒
        return {}